#!/bin/bash

# 定义仓库名称
repo_name=$1

# 检查仓库是否存在
check_and_handle_repo() {
    if ! aptly repo show "$repo_name" &> /dev/null; then
        echo "仓库$repo_name不存在，开始创建..."
        if ! aptly repo create "$repo_name"; then
            echo "创建仓库$repo_name时发生错误。"
            exit 1
        fi
        echo "仓库$repo_name创建成功。"
    else
        echo "仓库$repo_name已存在。"
    fi
    process_repo_content
}

# 处理仓库内容（添加包和发布）
process_repo_content() {
    if [ -d "/opt/$repo_name" ]; then
        echo "检测到目录/opt/$repo_name存在，开始添加包..."
        if ! aptly repo add "$repo_name" /opt/"$repo_name"/*.deb; then
            echo "添加包到仓库$repo_name时发生错误。"
            return 1
        fi
        echo "$repo_name包添加成功。"
        manage_publish "$repo_name"
    else
        echo "目录/opt/$repo_name不存在，跳过添加和发布步骤。"
    fi
}

# 管理发布
manage_publish() {
    local repo=$1
    case "$repo" in
        nfs-4.0)
            handle_publish "nfs4" "$repo"
            ;;
        nfs-5.0)
            handle_publish "nfs5" "$repo"
            ;;
        *)
            echo "未匹配到预定义的资源，跳过发布步骤。"
            ;;
    esac
}

# 处理发布的函数
handle_publish() {
    local publish_name=$1
    local repo=$2
    if ! aptly publish list | grep -q "^$publish_name "; then
        echo "发布$publish_name不存在，开始创建并发布..."
        if ! aptly publish repo -distribution="$publish_name" -component=main "$repo" "$publish_name"; then
            echo "发布$publish_name时发生错误。"
            return 1
        fi
    else
        echo "发布$publish_name已存在，开始更新发布..."
        if ! aptly publish update "$repo" "$publish_name"; then
            echo "更新发布$publish_name时发生错误。"
            return 1
        fi
    fi
    echo "发布$publish_name处理完成。"
}

# 主程序入口
check_and_handle_repo